package io.xxx.omni.translate

import io.xxx.omni.sync.Document
import io.xxx.omni.sync.DocumentMapper
import org.apache.pulsar.client.api.PulsarClient
import org.apache.pulsar.client.api.Schema
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component

interface Translator {

    val platform: String

    fun translate(document: Document)
}

interface TradeTranslator : Translator

interface RefundTranslator : Translator

/**
 * 将平台订单转换为标准格式
 */
@Component
class DocumentConverter : ApplicationRunner {

//    @Autowired
//    private lateinit var client: PulsarClient

    @Autowired
    private lateinit var documentMapper: DocumentMapper

    @Autowired
    private lateinit var applicationContext: ApplicationContext

    private lateinit var translatorMap: Map<String, List<Translator>>

    override fun run(args: ApplicationArguments) {
        val beanMap = applicationContext.getBeansOfType(Translator::class.java)
        translatorMap = beanMap.values.groupBy { it.platform }

//        client.newConsumer(Schema.INT64)
//            .subscriptionName("oms")
//            .topic("DOCUMENT_CREATED")
//            .messageListener { consumer, msg ->
//                val id = msg.value
//                val document = documentMapper.selectById(id)
//                if (document == null) {
//                    log.warn("Document[$id]不存在")
//                    consumer.acknowledge(msg)
//                    return@messageListener
//                }
//                val translators = translatorMap[document.platformCode]
//                if (translators != null) {
//                    val translator = if (translators.size == 1) {
//                        translators[0]
//                    } else {
//                        if (document.rsn.isNullOrBlank()) {
//                            translators.filterIsInstance<TradeTranslator>()[0]
//                        } else {
//                            translators.filterIsInstance<RefundTranslator>()[0]
//                        }
//                    }
//                    translator.translate(document)
//                    consumer.acknowledge(msg)
//                }
//            }
//            .subscribe()
    }

    companion object {
        private val log: Logger = LoggerFactory.getLogger(DocumentConverter::class.java)
    }
}